/**
 * 
 */
package com.monkeyboy.security.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 *
 * @author Gavin<br>
 *         2019年8月25日
 */
@RestController
public class ReturnAjaxOrHtmlController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private RequestCache requestCache = new HttpSessionRequestCache();
	// springsecurity的跳转策略
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	/**
	 * @throws IOException
	 * @Description<br>
	 * 					当springsecurity【需要身份认证】时候跳转到这个控制器<br>
	 *                  note：这个控制器只是针对授权登录这一步操作，不包括授权验证，验证密码身份这些错误的返回格式需要在自定义成功处理器和自定义失败处理器里面去操作
	 * 
	 * @Author Gavin</br>
	 *         2019年8月25日
	 */
	@RequestMapping("/authentication/require")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public Map<String, Object> requireAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> res = new HashMap<String, Object>();
		SavedRequest savedRequest = requestCache.getRequest(request, response);
		if (savedRequest != null) {
			String targetUrl = savedRequest.getRedirectUrl();
			logger.info("引发跳转的请求是：{}", targetUrl);
			if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {// 如果不是ajax请求就返回登录页面
				redirectStrategy.sendRedirect(request, response, "/mylogin.html");
			} else {// ajax请求
				res.put("code", "401");
				res.put("message", "未授权，请引导用户到登录页面。");
			}
		} else {// 如果使用默认的退出登录,savedRequest就会为空
			res.put("code", "401");
			res.put("message", "未授权，请引导用户到登录页面。");
		}
		return res;
	}
}
